package utils

import (
	"fmt"
	"math"
	"strconv"
	"strings"
)

//type Point struct {
//	X, Y float64
//}

// var ControlPoints = []Point{
// 	{X: 0, Y: 0},
// 	{X: 10, Y: 10},
// 	{X: 20, Y: 0},
// 	{X: 30, Y: 10},
// 	{X: 40, Y: 0},
// }

// 绘制贝塞尔曲线
//func DrawBezierCurve(controlPoints []Point) []Point {
//	// 计算曲线上的点
//	points := calculateBezierCurve(controlPoints)
//	// 绘制曲线
//	// drawCurve(points)
//	// fmt.Println("points: ", points)
//	return points
//}
//
//// 计算贝塞尔曲线上的点
//func calculateBezierCurve(controlPoints []Point) []Point {
//	// 定义曲线上的点
//	var points []Point
//	// 计算曲线上的点
//	for t := 0.0; t <= 1.0; t += 0.1 {
//		x, y := calculateBezierPoint(t, controlPoints)
//		points = append(points, Point{X: x, Y: y})
//	}
//	return points
//}
//
//// 计算贝塞尔曲线上的点
//func calculateBezierPoint(t float64, controlPoints []Point) (float64, float64) {
//	// 计算曲线上的点
//	var x, y float64
//	n := len(controlPoints) - 1
//	for i := 0; i <= n; i++ {
//		x += controlPoints[i].X * bernstein(n, i, t)
//		y += controlPoints[i].Y * bernstein(n, i, t)
//	}
//	return x, y
//}

// 计算伯恩斯坦多项式
func bernstein(n, i int, t float64) float64 {
	return float64(combination(n, i)) * math.Pow(t, float64(i)) * math.Pow(1-t, float64(n-i))
}

// 计算组合数
func combination(n, i int) int {
	return factorial(n) / (factorial(i) * factorial(n-i))
}

// 计算阶乘
//func factorial(n int) int {
//	if n == 0 {
//		return 1
//	}
//	return n * factorial(n-1)
//}

func SmoothBezier(points []string) []string {
	if len(points) < 3 {
		return points
	}

	smoothPoints := make([]string, 0)
	smoothPoints = append(smoothPoints, points[0])

	for i := 1; i < len(points)-1; i++ {
		p0 := parsePoint(points[i-1])
		p1 := parsePoint(points[i])
		p2 := parsePoint(points[i+1])

		// 计算贝塞尔曲线的中间点
		cx1 := (p0[0] + p1[0]) * 0.5
		cy1 := (p0[1] + p1[1]) * 0.5
		cx2 := (p1[0] + p2[0]) * 0.5
		cy2 := (p1[1] + p2[1]) * 0.5

		// 将中间点添加到平滑后的路径坐标点中
		smoothPoints = append(smoothPoints, formatPoint(cx1, cy1))
		smoothPoints = append(smoothPoints, formatPoint(cx2, cy2))
	}

	smoothPoints = append(smoothPoints, points[len(points)-1])

	return smoothPoints
}

// 解析坐标点字符串为浮点数切片
func parsePoint(point string) []float64 {
	coords := strings.Split(point, ",")
	x, _ := strconv.ParseFloat(coords[0], 64)
	y, _ := strconv.ParseFloat(coords[1], 64)
	return []float64{x, y}
}

// 格式化浮点数切片为坐标点字符串
func formatPoint(x, y float64) string {
	return fmt.Sprintf("%.4f,%.4f", x, y)
}

//func BezierN(point []string, n int) []string {
//
//}
